import React, { useState, useEffect } from 'react';
import {
  Card,
  Descriptions,
  Button,
  Tag,
  Space,
  Modal,
  message,
  Spin,
  Alert,
  Table,
  Popconfirm
} from 'antd';
import {
  ArrowLeftOutlined,
  EditOutlined,
  BookOutlined,
  UserOutlined,
  ClockCircleOutlined,
  EnvironmentOutlined,
  TeamOutlined
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import apiService from '../../services/apiService';
import moment from 'moment';

const CourseDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user, isAdmin, isTeacher, isStudent } = useAuth();
  const [course, setCourse] = useState(null);
  const [bookings, setBookings] = useState([]);
  const [loading, setLoading] = useState(true);
  const [bookingLoading, setBookingLoading] = useState(false);
  const [bookingModalVisible, setBookingModalVisible] = useState(false);
  const [userBooking, setUserBooking] = useState(null);

  useEffect(() => {
    loadCourseDetail();
    if (isAdmin() || isTeacher()) {
      loadCourseBookings();
    }
    if (isStudent()) {
      checkUserBooking();
    }
  }, [id]);

  const loadCourseDetail = async () => {
    try {
      setLoading(true);
      const data = isStudent() 
        ? await apiService.getCourseByIdPublic(id)
        : await apiService.getCourseById(id);
      setCourse(data);
    } catch (error) {
      message.error('加载课程详情失败');
      console.error('加载课程详情失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadCourseBookings = async () => {
    try {
      const data = await apiService.getBookingsByCourse(id);
      setBookings(data);
    } catch (error) {
      console.error('加载课程预订失败:', error);
    }
  };

  const checkUserBooking = async () => {
    try {
      const exists = await apiService.checkBookingExists(user.relatedId, id);
      if (exists) {
        const studentBookings = await apiService.getBookingsByStudent(user.relatedId);
        const booking = studentBookings.find(b => b.course.id === parseInt(id));
        setUserBooking(booking);
      }
    } catch (error) {
      console.error('检查用户预订失败:', error);
    }
  };

  const handleBookCourse = async () => {
    try {
      setBookingLoading(true);
      await apiService.createBooking({
        studentId: user.relatedId,
        courseId: parseInt(id)
      });
      message.success('预订成功');
      setBookingModalVisible(false);
      loadCourseDetail();
      checkUserBooking();
    } catch (error) {
      message.error('预订失败: ' + (error.response?.data?.message || error.message));
      console.error('预订课程失败:', error);
    } finally {
      setBookingLoading(false);
    }
  };

  const handleCancelBooking = async () => {
    try {
      setBookingLoading(true);
      await apiService.cancelBooking(userBooking.id);
      message.success('取消预订成功');
      setUserBooking(null);
      loadCourseDetail();
    } catch (error) {
      message.error('取消预订失败: ' + (error.response?.data?.message || error.message));
      console.error('取消预订失败:', error);
    } finally {
      setBookingLoading(false);
    }
  };

  const handleUpdateBookingStatus = async (bookingId, status) => {
    try {
      await apiService.updateBookingStatus(bookingId, status);
      message.success('状态更新成功');
      loadCourseBookings();
    } catch (error) {
      message.error('状态更新失败');
      console.error('更新预订状态失败:', error);
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'OPEN':
        return 'green';
      case 'FULL':
        return 'orange';
      case 'CLOSED':
        return 'red';
      default:
        return 'default';
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case 'OPEN':
        return '开放';
      case 'FULL':
        return '已满';
      case 'CLOSED':
        return '关闭';
      default:
        return status;
    }
  };

  const getBookingStatusColor = (status) => {
    switch (status) {
      case 'PENDING':
        return 'orange';
      case 'CONFIRMED':
        return 'green';
      case 'CANCELLED':
        return 'red';
      default:
        return 'default';
    }
  };

  const getBookingStatusText = (status) => {
    switch (status) {
      case 'PENDING':
        return '待确认';
      case 'CONFIRMED':
        return '已确认';
      case 'CANCELLED':
        return '已取消';
      default:
        return status;
    }
  };

  const canBookCourse = () => {
    if (!isStudent() || !course) return false;
    if (course.status !== 'OPEN') return false;
    if (userBooking && userBooking.status !== 'CANCELLED') return false;
    return true;
  };

  const bookingColumns = [
    {
      title: '学生姓名',
      dataIndex: ['student', 'name'],
      key: 'studentName'
    },
    {
      title: '学号',
      dataIndex: ['student', 'studentId'],
      key: 'studentId'
    },
    {
      title: '预订时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text) => moment(text).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status, record) => {
        if (isAdmin() || isTeacher()) {
          return (
            <Space>
              <Tag color={getBookingStatusColor(status)}>
                {getBookingStatusText(status)}
              </Tag>
              {status === 'PENDING' && (
                <Space>
                  <Button
                    size="small"
                    type="primary"
                    onClick={() => record && handleUpdateBookingStatus(record.id, 'CONFIRMED')}
                  >
                    确认
                  </Button>
                  <Button
                    size="small"
                    danger
                    onClick={() => record && handleUpdateBookingStatus(record.id, 'CANCELLED')}
                  >
                    拒绝
                  </Button>
                </Space>
              )}
            </Space>
          );
        }
        return (
          <Tag color={getBookingStatusColor(status)}>
            {getBookingStatusText(status)}
          </Tag>
        );
      }
    }
  ];

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!course) {
    return (
      <Alert
        message="课程不存在"
        description="您访问的课程不存在或已被删除"
        type="error"
        showIcon
      />
    );
  }

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate('/courses')}
        >
          返回课程列表
        </Button>
      </div>

      <Card
        title={
          <Space>
            <BookOutlined />
            {course.name}
            <Tag color={getStatusColor(course.status)}>
              {getStatusText(course.status)}
            </Tag>
          </Space>
        }
        extra={
          <Space>
            {isStudent() && (
              <>
                {userBooking && userBooking.status !== 'CANCELLED' ? (
                  <Popconfirm
                    title="确定要取消预订吗？"
                    onConfirm={handleCancelBooking}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button danger loading={bookingLoading}>
                      取消预订
                    </Button>
                  </Popconfirm>
                ) : (
                  <Button
                    type="primary"
                    disabled={!canBookCourse()}
                    onClick={() => setBookingModalVisible(true)}
                  >
                    {course.status === 'OPEN' ? '预订课程' : '课程已关闭'}
                  </Button>
                )}
              </>
            )}
            {(isAdmin() || isTeacher()) && (
              <Button
                icon={<EditOutlined />}
                onClick={() => navigate(`/courses/${id}/edit`)}
              >
                编辑课程
              </Button>
            )}
          </Space>
        }
      >
        <Descriptions bordered column={2}>
          <Descriptions.Item label="课程代码" span={1}>
            {course.code}
          </Descriptions.Item>
          <Descriptions.Item label="授课教师" span={1}>
            <Space>
              <UserOutlined />
              {course.teacher?.name} - {course.teacher?.department}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="学分" span={1}>
            {course.credit}
          </Descriptions.Item>
          <Descriptions.Item label="学时" span={1}>
            {course.hours}
          </Descriptions.Item>
          <Descriptions.Item label="开始时间" span={1}>
            <Space>
              <ClockCircleOutlined />
              {moment(course.startTime).format('YYYY-MM-DD HH:mm')}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="结束时间" span={1}>
            <Space>
              <ClockCircleOutlined />
              {moment(course.endTime).format('YYYY-MM-DD HH:mm')}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="上课地点" span={1}>
            <Space>
              <EnvironmentOutlined />
              {course.location}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="最大人数" span={1}>
            <Space>
              <TeamOutlined />
              {course.maxStudents}
            </Space>
          </Descriptions.Item>
          {course.description && (
            <Descriptions.Item label="课程描述" span={2}>
              {course.description}
            </Descriptions.Item>
          )}
        </Descriptions>

        {userBooking && (
          <Card
            title="我的预订"
            style={{ marginTop: 16 }}
            size="small"
          >
            <Descriptions size="small" column={1}>
              <Descriptions.Item label="预订状态">
                <Tag color={getBookingStatusColor(userBooking.status)}>
                  {getBookingStatusText(userBooking.status)}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="预订时间">
                {moment(userBooking.createdAt).format('YYYY-MM-DD HH:mm')}
              </Descriptions.Item>
            </Descriptions>
          </Card>
        )}
      </Card>

      {(isAdmin() || isTeacher()) && (
        <Card
          title="课程预订列表"
          style={{ marginTop: 16 }}
        >
          <Table
            columns={bookingColumns}
            dataSource={bookings}
            rowKey="id"
            pagination={{
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条预订记录`
            }}
          />
        </Card>
      )}

      <Modal
        title="确认预订"
        open={bookingModalVisible}
        onOk={handleBookCourse}
        onCancel={() => setBookingModalVisible(false)}
        confirmLoading={bookingLoading}
        okText="确认预订"
        cancelText="取消"
      >
        <p>您确定要预订课程 <strong>{course.name}</strong> 吗？</p>
        <Alert
          message="预订须知"
          description="预订后需要等待教师确认，确认后方可正式选课。"
          type="info"
          showIcon
          style={{ marginTop: 16 }}
        />
      </Modal>
    </div>
  );
};

export default CourseDetail;